package com.chenfeng.common.util;

import java.security.MessageDigest;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
		
@Component("encryptUtil")
public class EncryptUtil
{
	@Resource
	private RegexUtil regexUtil ;
	public String md5(String s)
	{
		char hexDigits[] =
		{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		try
		{
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++)
			{
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	//加密方法
	public String encryString(String password)
	{
		//获取32位的随机数
		String randStr = this.regexUtil.randString(32);
		//32随机数加+$MD5$
		String md5Str = randStr + "$MD5$";
		//32随机数加+$MD5$+password 字符串的组成的md5加密
		randStr = this.md5(md5Str+password);
		//32位随机数+（32随机数加+$MD5$+password字符串的组成的md5加密组成的密文存储到数据库中
		return md5Str+randStr;
	}
	//解密方法 deciphering:单词解密的意思 sour数据库存储的密码，password用户输入的密码
	public boolean deciphering(String sour,String password)
	{
		String randStr[] = sour.split("\\$");
		String md5Str = randStr[0] + "$" +randStr[1] +"$" +password;
		String  ciphertext = randStr[0] + "$" +randStr[1] +"$" + this.md5(md5Str);
		if(ciphertext.equalsIgnoreCase(sour))
		{
			return true;
		}
		return false;
	}
	//测试m5的加密版
	public static void main(String[] args)
	{
		EncryptUtil en = new EncryptUtil();
		System.out.println(en.md5("111111"));
		System.out.println(en.encryString("111111"));
		String sour = "M7c1v2IkHCxlaTGmgkhyYmvOgmRZPDzf$MD5$7F03227493430FBF835714D19BC44145";
		String password = "11111";
		System.out.println(en.deciphering(sour, password));
	}
}
